const moment = require('moment')
const log = console.log
const request = require('request')

const HTADERS = {
  //请求头
  'content-type': 'text/html; charset=utf-8',
  Accept: '*/*',
  'User-Agent':
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
  Cookie:
    '__cfduid=d3d9ff48b8f0e64074a0fdd98baf293f41578476784; PHPSESSID=kqjdkmfq9kgu3haf22jt4hdlsu',
  'Access-Token': 'B1D377A09A35B8D9B326AF31A20152FB',
  Timestamp: moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
}

var params = {
  open_date: moment(new Date()).format('YYYY-MM-DD'),
  forecast_quantity: '6',
  location: 5,
  isSplit: true,
  isSplit_num: 2
}

const search_list = () => {
  return new Promise((resolve, reject) => {
    request(
      {
        url: 'https://www.k55655.com/v1/ForecastRanking?code=mjssc',
        headers: HTADERS
      },
      (err, res, body) => {
        // console.log(body)
        if (!err && res.statusCode == 200) {
          resolve(JSON.parse(body))
        }
        if (res.statusCode == 408) {
          console.log('cookie过期')
        }
        reject(err)
      }
    )
  })
}
const cast_plan = body => {
  var list_one = body.data[changeT()].list
  return PromiseForEach(list_one, item => {
    return new Promise((resolve, reject) => {
      request(
        {
          url:
            'https://www.k55655.com/v1/ForecastPlan?code=mjssc&expert_id=' +
            item.expert_id +
            '&open_date=' +
            params.open_date +
            '&forecast_quantity=' +
            item.forecast_quantity +
            '&location=' +
            item.location_key +
            '',
          headers: HTADERS
        },
        (err, res, body) => {
          if (!err && res.statusCode == 200) {
            body = JSON.parse(body)
            body.name = item.name
            resolve(body)
          }
        }
      )
    })
  })
}

const changeT = () => {
  return params.forecast_quantity == '4'
    ? '0'
    : params.forecast_quantity == '5'
    ? '1'
    : '2'
}

const forecastPlan = obj => {
  var data = obj.data.expert_forecast_data_list
  var number = 0
  var push_arr = []
  data.forEach((item, i) => {
    if (item.length == 1) {
      return
    }
    if (item[0].deadline_win_or_lose == '暂无') {
      item[0] = item[1]
    }
    number += parseInt(item[0].deadline_win_or_lose)
    if (params.isSplit) {
      if (i % params.isSplit_num == 0) {
        push_arr.push(number)
        number = 0
      }
    }
  })
  return params.isSplit ? push_arr : number
}

//循环标签请求数据
const PromiseForEach = (arr, callback) => {
  let realResult = []
  let result = Promise.resolve()
  arr.forEach((tag, index) => {
    result = result.then(() => {
      return callback(tag).then(res => {
        realResult.push(res)
      })
    })
  })
  return result.then(() => {
    return realResult
  })
}

//格式化数据
const initInData = p_li => {
  let hash = {}
  var newArr = p_li.reduceRight((item, next) => {
    hash[next.location] ? '' : (hash[next.location] = true && item.push(next))
    return item
  }, [])
  newArr.forEach((item, ky) => {
    item.forecast_numbers = []
    item.count = 0
    p_li.forEach((value, key) => {
      if (item.location == value.location) {
        item.count += 1
        item.forecast_numbers = item.forecast_numbers.concat(
          value.forecast_numbers
        )
      }
    })
  })
  newArr.sort((a, b) => {
    return b.count - a.count
  })
  var p_data = newArr[0]
  p_data.forecast_numbers.sort((a, b) => {
    return a - b
  })
  var kyhhz = Object.entries(uniqueCount(p_data.forecast_numbers))
  kyhhz.sort((a, b) => {
    return b[1] - a[1]
  })
  kyhhz = kyhhz.splice(0, 6)
  var opzx = []
  kyhhz.forEach(item => {
    opzx.push(item[0])
  })
  p_data.forecast_numbers = opzx
  return p_data
}

//获取在数组中出现的次数
const uniqueCount = arr => {
  var result = [],
    count = {}
  for (var i = 0, len = arr.length; i < len; i++) {
    var temp = arr[i]
    if (!count[temp]) {
      result.push(temp)
      count[temp] = 1
    } else {
      count[temp]++
    }
  }
  return count
}

async function rankIng(token) {
  HTADERS['Access-Token'] = token.replace(/"/g, '')
  HTADERS['Timestamp'] = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
  var result = await search_list()
  var others = await cast_plan(result)
  var p_li = []
  others.forEach((item, i) => {
    var obj = item.data.expert_forecast_data_list[0][0]
    // console.log(obj.expert_name, obj.forecast_numbers, obj.expect, obj.location)
    p_li.push({
      location: obj.location,
      forecast_numbers: obj.forecast_numbers,
      expect: obj.expect
    })
  })
  return initInData(p_li)
}

module.exports = rankIng
